import {Component, OnInit} from '@angular/core';
import {Router, ActivatedRoute} from "@angular/router";
import {PageSubject} from "../../../../util/page-subject";
import {ResponseUtil} from "../../../../util/response-util";
import {OneDialogService} from "../../../../widgets/one-dialog/one-dialog.service";
import {UsersService} from "../users.service";
import {Path} from "../../../../portal/admin/admin-breadcrumb/breadcrumb";
import {Account} from "../../../permission/accounts/account";
import {MsgResult} from "../../../../models/msg-result";
import {MsgConstants} from "../../../../constants/constants";
import {Validators, FormGroup, FormBuilder} from "@angular/forms";

@Component({
  selector: 'app-user-creat-acc',
  templateUrl: './user-creat-acc.component.html'
})
export class UserCreatAccComponent implements OnInit {

  userId: string;

  account: Account;

  accountForm :FormGroup;

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private fb: FormBuilder,
    private pageSubject: PageSubject,
    private responseUtil: ResponseUtil,
    private dialogService: OneDialogService,
    private usersService: UsersService
  ) {
    this.initObject();
  }

  ngOnInit() {
    //初始化面包屑导航
    this.pushPage();
    //获取数据
    if (!!this.route.snapshot.params["id"]) {
      this.userId = this.route.snapshot.params["id"];
    }
  }

  /**
   * 面包屑导航
   */
  pushPage() {
    let path = new Path("用户系统", "");
    this.pageSubject.pushPage("用户管理", "创建账户", path);
  }

  /**
   * 构造表单
   */
  private buildForm(): void {
    this.accountForm = this.fb.group({
      'id': [this.account.id],
      'accountName': [this.account.accountName, [
        Validators.required,
        Validators.minLength(6),
        Validators.maxLength(16),
        Validators.pattern(/^[A-Za-z0-9_]+$/)
      ]]
    });

    this.accountForm.valueChanges.subscribe(
      data => this.onValueChanged(data)
    );
    this.onValueChanged();
  }


  /**
   * 值变化监听
   * @param data
   */
  onValueChanged(data?: any) {
    if (!this.accountForm) {
      return;
    }
    const form = this.accountForm;
    for (const field in this.formErrors) {
      this.formErrors[field] = '';
      const control = form.get(field);
      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }
  }

  /**
   * 校验字段
   * @type {{name: string; code: string}}
   */
  formErrors = {
    'accountName': '',
  };

  /**
   * 校验提示信息
   * @type {{name: {required: string; maxlength: string}; code: {required: string; maxlength: string; pattern: string}}}
   */
  validationMessages = {
    'accountName': {
      'required': '账户名不能为空',
      'minlength': '长度不能低于6',
      'maxlength': '长度不能超过16',
      'pattern': '只能由字母、数字、下划线组成'
    }
  };

  /**
   * 创建账户
   */
  onSubmit() {
    this.account = this.accountForm.value;
    this.usersService.createAccountByUserCode(this.account).subscribe(
      result => this.responseUtil.success(result, this.processCreateAccountResult),
      message => this.responseUtil.error(message)
    );
  }

  /**
   * 获取账户信息     getCreateAccByUserCodeLog
   * @param result
   */
  private processCreateAccountResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      let accountName = result.data.accountName;
      let id = result.data.id;
      this.saveAllocationAccount(accountName, id);
      this.dialogService.modalSuccessWithCancelBtn("创建并分配成功！", () => this.cancelAccountAdd());
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 分配账户
   */
  private saveAllocationAccount(accountName, id) {
    this.usersService.updateUserForAssignAcc(this.userId, accountName, id).subscribe(
      result => this.responseUtil.success(result, this.processAssignAccResult),
      message => this.responseUtil.error(message)
    );
  }

  /**
   * 取消创建
   */
  cancelAccountAdd() {
    this.router.navigate(['..'], {relativeTo: this.route});
  }

  /**
   *  对分配账户结果处理
   * @param result
   */
  private processAssignAccResult = (result: MsgResult) => {
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 实例化对象
   */
  private initObject() {
    this.account =new Account("","","","","","","","","","0","0","0","0","0");
    this.buildForm();
  }

}
